package com.yn.xgame.game;

import com.yn.xgame.XAssert;
import com.yn.xgame.pb.GateClientProto;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * RoomTable
 * 房间里面的桌子
 * Created by wangboo on 17/7/15.
 */
public class RoomTable {

    // 游戏状态，未开始
    public static final int STATE_NO_START = 0;
    // 已经开始游戏
    public static final int STATE_IN_GAME = 1;

    protected int tableId;
    protected int maxSize;
    protected int opTimeout = 10; // 游戏期间，操作时间
    protected int state = STATE_NO_START;
    protected int hostIdx = -1; // 房主位置

    protected ArrayList<RoomPlayer> inGamePlayerList;
    protected LinkedList<RoomPlayer> waitingToJoinPlayerList;

    private GateClientProto.TableSimpleInfo pbTableSimpleInfo;

    public RoomTable(int tableId, int maxSize) {
        this.tableId = tableId;
        this.maxSize = maxSize;
        XAssert.isTrue(maxSize > 0);
        inGamePlayerList = new ArrayList<>(maxSize);
        waitingToJoinPlayerList = new LinkedList<>();
    }

    public int getState() {
        return state;
    }

    public ArrayList<RoomPlayer> getInGamePlayerList() {
        return inGamePlayerList;
    }

    public boolean canPlayerJoin() {
        int size = getOnlineCount();
        if (size >= maxSize) return false;
        if (waitingToJoinPlayerList != null) size += waitingToJoinPlayerList.size();
        return size < maxSize;
    }

    public void joinPlayer(RoomPlayer player) {
        XAssert.isTrue(canPlayerJoin());
        if (state == STATE_IN_GAME) {
            // 游戏中时，加入到排队队列
            waitingToJoinPlayerList.add(player);
        } else {
            // 游戏未开始，直接加入
            inGamePlayerList.add(player);
            // 广播
        }
    }

    public int getOnlineCount() {
        return (int) inGamePlayerList.stream().filter(RoomPlayer::isOnline).count();
    }

    public void onPlayerLeave(int uid) {
        inGamePlayerList.removeIf(p -> p.userId == uid);
        waitingToJoinPlayerList.removeIf(p -> p.userId == uid);
    }

    public void broadcastExcept(int uid, GateClientProto.G2CMessage msg) {
    }

    protected void onGameStart() {
    }

    protected void onFinish() {
    }

    // 房间是否为空
    public boolean isEmpty() {
        return state == STATE_NO_START && inGamePlayerList.size() == 0;
    }

    public boolean isNotEmpty() {
        return state == STATE_IN_GAME || inGamePlayerList.size() > 0;
    }

    public GateClientProto.TableSimpleInfo getRoomSimpleInfo() {
        return pbTableSimpleInfo == null ? updateRoomSimpleInfo() : pbTableSimpleInfo;
    }

    public GateClientProto.TableSimpleInfo updateRoomSimpleInfo() {
        GateClientProto.TableSimpleInfo.Builder bu = GateClientProto.TableSimpleInfo.newBuilder();
        bu.setState(state).setTableId(tableId).setTableId(hostIdx);
        inGamePlayerList.forEach(p -> bu.addInfo(p.updatePlayerSimpleInfo()));
        pbTableSimpleInfo = bu.build();
        return pbTableSimpleInfo;
    }
}
